package com.py.framework.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.core.utils.BeanUtil;
import com.py.framework.entity.MenuEntity;
import com.py.framework.enums.MenuType;
import com.py.framework.service.MenuResourceService;

/**
 * 菜单资源Controller
 * @author Leegern
 * @date   2018年4月23日
 */
@RestController
@RequestMapping("/menuresource")
public class MenuResourceController extends SystemController {
	
	/**
	 * 未读取到配置文件中的顶级资源名称，使用默认值
	 */
	private static final String topName = "顺义区公共信用信息平台";

	@Value("${topMenuName}")
	private String topMenuName;

	private static Map<String, Object> topResource = new HashMap<>();
	{
		topResource.put("id", 0);
		topResource.put("parentId", 0);
		topResource.put("allParentId", null);
		topResource.put("menuType", 1);
		topResource.put("linkUrl", null);
		topResource.put("routeAddr", null);
		topResource.put("orderBy", 1);
		topResource.put("isWinOpen", 2);
		topResource.put("parentMenuName", "");
		topResource.put("menuName", StringUtils.isNotBlank(topMenuName) ? topMenuName : topName);
	}

	@Autowired
	private MenuResourceService menuResourceService;
	
	
	/**
	 * @api {post} /menuresource/addMenuResourceInfo.json 添加菜单资源实体
	 * @apiName addMenuResourceInfo
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParam {MenuEntity} entity 菜单资源实体
	 * @apiParam {String} menuName 菜单名称
	 * @apiParam {long} parentId 父节点ID
	 * @apiParam {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiParam {String} linkUrl 后台路由
	 * @apiParam {String} routeAddr 前台路由地址
	 * @apiParam {String} icon ICON图标
	 * @apiParam {int} orderBy 排序
	 * @apiParam {int} isShow 是否显示，1：是，2：否
	 * @apiParam {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiParamExample {json} 请求参数示例
	 *  {"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":0,"data": ""}
	 */
	@RequestMapping(value = "/addMenuResourceInfo", method = RequestMethod.POST)
	public RestServiceResult<Object> addMenuResourceInfo(@RequestBody MenuEntity entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				menuResourceService.addMenuResourceInfo(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("添加失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /menuresource/queryMenuResourceForPage.json 分页插叙菜单资源列表信息
	 * @apiName queryMenuResourceForPage
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParam {int} page  当前页码
	 * @apiParam {int} limit 每页条数
	 * @apiParam {String} menuName 菜单名称
	 * @apiParam {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiParam {long}  parentId 父ID
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} menuName 菜单名称
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} linkUrl 后台路由
	 * @apiSuccess {String} routeAddr 前台路由地址
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccess {String} parentMenuName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":3,"data": [{"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}]}
	 */
	@RequestMapping(value = "/queryMenuResourceForPage", method = RequestMethod.POST)
	public RestServiceResult<List<MenuEntity>> queryMenuResourceForPage(int page, int limit, String menuName, 
			@RequestParam(value="menuType", required=false, defaultValue="0")int menuType,
			@RequestParam(value="parentId", required=false, defaultValue="0")long parentId) {
		Map<String, Object> params = new HashMap<>();
		Page pager = super.getPage(page, limit);
		params.put("page", pager);
		params.put("menuName", menuName);
		params.put("menuType", menuType);
		params.put("parentId", parentId);
		List<MenuEntity> datas = menuResourceService.queryMenuResourceForPage(params);
		return super.getPageSuccessRestServiceResult(pager.getTotalCount(), datas);
	}
	
	/**
	 * @api {post} /menuresource/getAllMenuResources.json 查询所有菜单资源数据
	 * @apiName getAllMenuResources
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} menuName 菜单名称
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} linkUrl 后台路由
	 * @apiSuccess {String} routeAddr 前台路由地址
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccess {String} parentMenuName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":3,"data": [{"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}]}
	 */
	@RequestMapping(value = "/getAllMenuResources", method = RequestMethod.POST)
	public RestServiceResult<List<Map<String, Object>>> getAllMenuResources() {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		String name = StringUtils.isNotBlank(topMenuName) ? topMenuName : topName;
		topResource.put("menuName", name);
		result.add(topResource);
		Map<String, Object> item = null;
		List<MenuEntity> datas = menuResourceService.getMenuResourceByParentId(null);
		if (! CollectionUtils.isEmpty(datas)) {
			for (MenuEntity menuEntity : datas) {
				try {
					item = BeanUtil.populateBean2Map(menuEntity);
					if (null != item) {
						// if (null != menuEntity && 1 == menuEntity.getMenuType()) {
						// item.put("parentMenuName", name);
						// }
						item.remove("icon");
						result.add(item);
					}
				} catch (Exception e) {
					ExceptionLogger.error(e);;
				}
			}
		}
		return super.getSuccessRestServiceResult(result);
	}
	
	/**
	 * @api {post} /menuresource/getMenuResourceByParentId.json 根据父Id查询所有子节点数据
	 * @apiName getMenuResourceByParentId
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParam {String}  parentId 父Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} menuName 菜单名称
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} linkUrl 后台路由
	 * @apiSuccess {String} routeAddr 前台路由地址
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccess {String} parentMenuName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":3,"data": [{"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}]}
	 */
	@RequestMapping(value = "/getMenuResourceByParentId", method = RequestMethod.POST)
	public RestServiceResult<List<MenuEntity>> getMenuResourceByParentId(String parentId) {
		List<MenuEntity> datas = null;
		if (StringUtils.isNotBlank(parentId)) {
			datas = menuResourceService.getMenuResourceByParentId(parentId);
		}
		return super.getSuccessRestServiceResult(datas);
	}
	
	/**
	 * @api {post} /menuresource/getSysMenuResource.json 获取系统菜单数据
	 * @apiName getSysMenuResource
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} menuName 菜单名称
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} linkUrl 后台路由
	 * @apiSuccess {String} routeAddr 前台路由地址
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccess {String} parentMenuName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":3,"data": [{"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}]}
	 */
	@RequestMapping(value = "/getSysMenuResource", method = RequestMethod.POST)
	public RestServiceResult<List<MenuEntity>> getSysMenuResource() {
		// 根据菜单类型查询菜单资源数据, 1：子系统
		List<MenuEntity> datas = menuResourceService.getMenuResourceByMenuType(MenuType.TYPE_1.getValue());
		return super.getSuccessRestServiceResult(datas);
	}
	
	/**
	 * @api {post} /menuresource/findOneMenuResource.json 根据Id查询菜单资源实体
	 * @apiName findOneMenuResource
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParam {long}  id 菜单资源Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} menuName 菜单名称
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} linkUrl 后台路由
	 * @apiSuccess {String} routeAddr 前台路由地址
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccess {String} parentMenuName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":0,"data": {"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}}
	 */
	@RequestMapping(value = "/findOneMenuResource", method = RequestMethod.POST)
	public RestServiceResult<MenuEntity> findOneMenuResource(long id) {
		MenuEntity data = null;
		if (id > Constants.NUMBER_ZERO) {
			data = menuResourceService.findOneMenuResource(id);
		}
		if (null != data && 1 == data.getMenuType()) {
			String name = StringUtils.isNotBlank(topMenuName) ? topMenuName : topName;
			data.setParentMenuName(name);
		}
		return super.getSuccessRestServiceResult(data);
	}
	
	/**
	 * @api {post} /menuresource/updateMenuResource.json 更新菜单资源信息
	 * @apiName updateMenuResource
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParam {MenuEntity}  entity 菜单资源
	 * @apiParam {String} menuName 菜单名称
	 * @apiParam {long} parentId 父节点ID
	 * @apiParam {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiParam {String} linkUrl 后台路由
	 * @apiParam {String} routeAddr 前台路由地址
	 * @apiParam {String} icon ICON图标
	 * @apiParam {int} orderBy 排序
	 * @apiParam {int} isShow 是否显示，1：是，2：否
	 * @apiParam {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiParamExample {json} 请求参数示例
	 *  {"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":0,"data": ""}
	 */
	@RequestMapping(value = "/updateMenuResource", method = RequestMethod.POST)
	public RestServiceResult<Object> updateMenuResource(@RequestBody MenuEntity entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				menuResourceService.updateMenuResource(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /menuresource/batchDelMenuResource.json 批量删除菜单资源
	 * @apiName batchDelMenuResource
	 * @apiVersion 0.0.1
	 * @apiGroup 菜单资源管理 
	 * @apiParam {String}  ids 菜单资源Id集合
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *    {"code":0,"msg":"","count":0,"data": ""}
	 */
	@RequestMapping(value = "/batchDelMenuResource", method = RequestMethod.POST)
	public RestServiceResult<Object> batchDelMenuResource(String ids) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (StringUtils.isNotBlank(ids)) {
			try {
				menuResourceService.batchDelMenuResource(super.convert2Long(ids));
			} catch (ServiceException e) {
				result = super.getFailedRestServiceResult(e.getMessage());
				ExceptionLogger.error(e);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("删除失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
}